package vn.com.unit.springmvc.repo;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import vn.com.unit.springmvc.domain.AssetType;

@Repository
@Transactional
public class AssetTypeDaoImpl implements AssetTypeDao {
	@Autowired
	private EntityManager em;

	public AssetType findById(Long id) {
		return em.find(AssetType.class, id);
	}

	public AssetType findByCode(String code) {
		// CriteriaBuilder builder = em.getCriteriaBuilder();
		// CriteriaQuery<AssetType> criteria =
		// builder.createQuery(AssetType.class);
		// Root<AssetType> assetType = criteria.from(AssetType.class);
		// criteria.select(assetType).where(builder.equal(assetType.get("code"),
		// code));
		// TypedQuery<AssetType> query = em.createQuery(criteria);
		// if(query == null || query.getFirstResult() == 0) {
		// return null;
		// }
		//
		// return query.getSingleResult();

		List<AssetType> list = em
				.createQuery(
						"select assettype from AssetType as assettype where assettype.code = ?1")
				.setParameter(1, code).getResultList();
		if (list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}

	public List<AssetType> findByName(String name) {
		List<AssetType> list = em
				.createQuery(
						"select assettype from AssetType as assettype where assettype.name = ?1")
				.setParameter(1, name).getResultList();
		return list;
	}

	public List<AssetType> findAllOrderedByName() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<AssetType> criteria = cb.createQuery(AssetType.class);
		Root<AssetType> assetType = criteria.from(AssetType.class);
		criteria.select(assetType).orderBy(cb.asc(assetType.get("name")));
		return em.createQuery(criteria).getResultList();
	}

	public void register(AssetType assetType) {
		em.persist(assetType);
		return;
	}

	public void update(AssetType assetType) {
		em.merge(assetType);
		return;
	}

	public void delete(Long id) {
		AssetType a = findById(id);
		em.remove(a);
		return;
	}
}
